package com.zhanglong;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import java.util.Map;

public class ZhanglongSpringApplication {

    public static void run(Class<?> clazz) {
        //创建Spring容器
        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        applicationContext.register(clazz);
        applicationContext.refresh();

        WebServer webServer = getWebServer(applicationContext);
        webServer.start();

        //startTomcat(applicationContext);
    }

    private static WebServer getWebServer(ApplicationContext applicationContext) {

        Map<String, WebServer> webServer = applicationContext.getBeansOfType(WebServer.class);

        if(webServer.isEmpty()) {
            throw new NullPointerException();
        }

        if(webServer.size() > 1) {
            throw new IllegalStateException();
        }

        return webServer.values().stream().findFirst().get();
    }

    //启动tomcat
   /* private static void startTomcat(WebApplicationContext applicationContext) {
        Tomcat tomcat = new Tomcat();

        Server server = tomcat.getServer();
        Service service = server.findService("Tomcat");

        Connector connector = new Connector();
        connector.setPort(8081);

        Engine engine = new StandardEngine();
        engine.setDefaultHost("localhost");

        Host host = new StandardHost();
        host.setName("localhost");

        String contextPath = "";
        StandardContext standardContext = new StandardContext();
        standardContext.setPath(contextPath);
        standardContext.addLifecycleListener(new Tomcat.FixContextListener());

        host.addChild(standardContext);
        engine.addChild(host);

        service.setContainer(engine);
        service.addConnector(connector);

        //构建DispatcherServlet时需要传入IOC容器，目的是去找到controller(bean)
        tomcat.addServlet(contextPath, "dispatcher", new DispatcherServlet(applicationContext));
        standardContext.addServletMappingDecoded("/*", "dispatcher");

        try {
            tomcat.start();
        } catch (LifecycleException e) {
            throw new RuntimeException(e);
        }
    }*/
}
